﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEngine;

public class LoadCSV {

    private Dictionary<int, T_CsvData> LoadCsvData<T_CsvData>(string csvFilePath)
    {
        Dictionary<int, T_CsvData> dic = new Dictionary<int, T_CsvData>();
        /* 从CSV文件读取数据 */
        Dictionary<string, Dictionary<string, string>> result= LoadCsvFile(csvFilePath); ;
        /* 遍历每一行数据 */
        foreach (string ID in result.Keys)
        {
            /* CSV的一行数据 */
            Dictionary<string, string> datas = result[ID];
            /* 读取Csv数据对象的属性 */
            PropertyInfo[] props = typeof(T_CsvData).GetProperties();
            /* 使用反射，将CSV文件的数据赋值给CSV数据对象的相应字段，要求CSV文件的字段名和CSV数据对象的字段名完全相同 */
            T_CsvData obj = Activator.CreateInstance<T_CsvData>();
            foreach (PropertyInfo pi in props)
            {
                pi.SetValue(obj, Convert.ChangeType(datas[pi.Name], pi.PropertyType), null);
            }
            /* 按ID-数据的形式存储 */
            dic[Convert.ToInt32(ID)] = obj;
        }
        return dic;
    }

    public static Dictionary<string, Dictionary<string, string>> LoadCsvFile(string filePath)
    {
        Dictionary<string, Dictionary<string, string>> result = new Dictionary<string, Dictionary<string, string>>();
        string[] fileData = File.ReadAllLines(filePath);
        /* CSV文件的第一行为Key字段，第二行开始是数据。第一个字段一定是ID。 */
        string[] keys = fileData[0].Split(',');
        for (int i = 1; i < fileData.Length; i++)
        {
            string[] line = fileData[i].Split(',');
            /* 以ID为key值，创建一个新的集合，用于保存当前行的数据 */
            string ID = line[0];
            result[ID] = new Dictionary<string, string>();
            for (int j = 0; j < line.Length; j++)
            {
                /* 每一行的数据存储规则：Key字段-Value值 */
                result[ID][keys[j]] = line[j];
            }
        }
        return result;
    }
    public static Dictionary<string, Dictionary<string, string>> LoadCsvFromString(string txt)
    {
        Dictionary<string, Dictionary<string, string>> result = new Dictionary<string, Dictionary<string, string>>();
        string[] fileData = txt.Trim().Split('\n');
        string[] keys = fileData[0].TrimEnd().Split(',');
        for (int i = 1; i < fileData.Length; i++)
        {
            string[] line = fileData[i].Split(',');
            /* 以ID为key值，创建一个新的集合，用于保存当前行的数据 */
            string ID = line[0];
            result[ID] = new Dictionary<string, string>();
            for (int j = 0; j < line.Length; j++)
            {
                /* 每一行的数据存储规则：Key字段-Value值 */
                result[ID][keys[j]] = line[j];
            }
        }
        return result;
    }


}
